package ca.etsmtl.logti.log619.lab05.filter;

import java.io.IOException;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import ca.etsmtl.logti.log619.lab05.utilities.BayesFilterBuilder;
import ca.etsmtl.logti.log619.lab05.utilities.EmailSplicer;
import ca.etsmtl.logti.log619.lab05.utilities.Word;


public class BayesFilter implements EmailFilter {

	final String NAME = "Bayes filter";

	@Override
	public String getFilterName() {
		return this.NAME;
	}

	@Override
	public byte checkSpam(MimeMessage message) {
		byte spamVal = CANT_SAY;

		try {
			byte value = analyze(message);
			if(value > 0)
				spamVal = value;			
			
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}

		return spamVal;
	}

	public byte analyze(MimeMessage message) throws MessagingException {

		
		String[] messages;
		double score = 0;
		int wordCounter = 0;
		try {
			
			messages = EmailSplicer.getMessageContent(message);
		
			for (int i = 0; i < messages.length; i++) {
				
				for(Word word : BayesFilterBuilder.wordDatabase.values()){
					if (messages[i].contains(word.getWord())){	
						
						score += word.getPSpam();	
						wordCounter++;
					}
				}
			}
		
		} catch (MessagingException e) {
			return (byte)100;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return (byte)100;
		}
		
		//System.out.println("Score "+ score + " Counter : "+ wordCounter);
		//System.out.println(score/wordCounter);
		
		return (byte) (score/wordCounter);
	}

	@Override
	public boolean enabled() {
		return true;
	}

	@Override
	public byte getConfidenceLevel() {
		return 75;
	}
}